package com.mall.product.api.controller;

import com.mall.common.util.JsonResult;
import com.mall.model.*;
import com.mall.product.service.ProductNotificationService;
import com.mall.service.ProductService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*商品控制器*/
@RestController
@RequestMapping("/api/products")
public class ProductController {

    @Autowired
    private ProductService productService;
    

    private ProductNotificationService notificationService;


    @GetMapping("/ping")
    public String ping() { return "ok"; }

    /**
     * 创建商品
     */
    @PostMapping
    public JsonResult<Long> create(@RequestBody Product product) {
        return JsonResult.success(productService.create(product));
    }

    /*更新商品*/
    @PutMapping("/upte")
    public JsonResult<Boolean> update(@RequestBody Product product) {

        return JsonResult.success(productService.updateById(product));
    }

    /*商品详情*/
    @GetMapping("/{id}")
    public  JsonResult<Product> detail(@PathVariable("id") Long id) {
        return JsonResult.success(productService.getById(id));
    }


    @GetMapping
    public JsonResult<Map<String,Object>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                               @RequestParam(value = "brandId", required = false) Long brandId,
                                               @RequestParam(value = "categoryId", required = false) Long categoryId,
                                               @RequestParam(value = "status", required = false) Integer status,
                                               @RequestParam(value = "isHot", required = false) Integer isHot,
                                               @RequestParam(value = "minPrice", required = false) BigDecimal minPrice,
                                               @RequestParam(value = "maxPrice", required = false) BigDecimal maxPrice,
                                               @RequestParam(value = "page", defaultValue = "1") Integer page,
                                               @RequestParam(value = "size", defaultValue = "10") Integer size) {
        List<Product> data = productService.pageQuery(keyword,brandId,categoryId,status,isHot,minPrice,maxPrice,page,size);
        long total = productService.count(keyword, brandId, categoryId, status, isHot, minPrice, maxPrice);

        Map<String,Object> res = new HashMap<>();
        res.put("total",total);
        res.put("list",data);

        return JsonResult.success(res);
    }

    //根据品牌Id查询
    @GetMapping("/brand/{brandId}")
    List<Product> getProductsByBrand(@PathVariable("brandId") Long brandId){
        return productService.getByBrandId(brandId,1);
    }

    //根据分类查询
    @GetMapping("/category/{categoryId}")
    public JsonResult<List<Product>> byCategory(@PathVariable("categoryId") Long categoryId,@RequestParam(value = "status", required = false) Integer status){
        return  JsonResult.success(productService.getByCategoryId(categoryId,status));
    }

    //更新状态 上下架
    @PatchMapping("/{id}/status")
    public JsonResult<Boolean> updateStatus(@PathVariable("id") Long id,@RequestParam(value = "status") Integer status) {
        // 获取原商品信息
        Product oldProduct = productService.getById(id);
        String oldStatus = oldProduct.getStatus() == 1 ? "上架" : "下架";
        
        // 更新状态
        boolean result = productService.updateStatus(id, status);
        

        
        return JsonResult.success(result);
    }

    //更新热门标记
    @PatchMapping("/{id}/hot")
    public JsonResult<Boolean> updateHot(@PathVariable("id") Long id,@RequestParam(value = "isHot") Integer isHot) {
        return JsonResult.success(productService.updateisHot(id,isHot));
    }

    //更新库存
    @PatchMapping("/{id}/stock")
    public JsonResult<Boolean> updateStock(@PathVariable("id") Long id,@RequestParam(value = "stock") Integer stock) {
        // 获取原商品信息
        Product oldProduct = productService.getById(id);
        Integer oldStock = oldProduct.getStock();
        
        // 更新库存
        boolean result = productService.updateStock(id, stock);
        

        return JsonResult.success(result);
    }

    //更新价格
    @PatchMapping("/{id}/price")
    public JsonResult<Boolean> updateprice(@PathVariable("id") Long id,@RequestParam(value = "price") BigDecimal price){
        // 获取原商品信息
        Product oldProduct = productService.getById(id);
        Double oldPrice = oldProduct.getPrice().doubleValue();
        
        // 更新价格
        boolean result = productService.updatePrice(id, price);
        
        if (result) {
            // 获取更新后的商品信息
            Product newProduct = productService.getById(id);
            Double newPrice = newProduct.getPrice().doubleValue();
            
            // 发送价格变化通知
            int[] userIds = {1, 2, 3}; // 示例用户ID，实际应该从数据库查询
            notificationService.sendPriceChangeNotification(newProduct, oldPrice, newPrice, userIds);
        }
        
        return JsonResult.success(result);
    }

    //逻辑删除
    @DeleteMapping("/{id}")
    public JsonResult<Boolean> delete(@PathVariable("id") Long id) {
        return JsonResult.success(productService.softDeleted(id));
    }

    @PostMapping("/{id}/{jianshaoStock}")
    public JsonResult<Boolean> deductStock(
            @PathVariable("id") Long id,
            @PathVariable("jianshaoStock") Integer jianshaoStock) {
        try {
            boolean success = productService.jianshaoStock(id, jianshaoStock);
            return JsonResult.success(success);
        } catch (IllegalArgumentException e) {
           throw new IllegalArgumentException("库存不足！");
        }
    }

    @PostMapping("/rollback/{id}/{jianshaoStock}")
    JsonResult<Boolean> restoreStock(@PathVariable("id") Long id,
                                     @PathVariable("jianshaoStock") Integer jianshaoStock) {
        try {
            boolean success = productService.restorejianshaoStock(id,jianshaoStock);
            return JsonResult.success(success);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("回滚失败！");
        }

    }

    @GetMapping("/key-metrics")
    ProductBack getKeyMetrics(@RequestParam LocalDate startDate,
                              @RequestParam LocalDate endDate){
     com.mall.model.ProductBack p = productService.getKeyMetrics(startDate,endDate);
     return p;

    }

    @GetMapping("/productsByCategory")
    List<Map<String, Object>> getProductCount(@RequestParam LocalDate startDate,
                                              @RequestParam LocalDate endDate){
        return productService.getProductcount(startDate,endDate);

    }


    @GetMapping("/getStockBack")
    List<Map<String, Object>> getStockBack(@RequestParam LocalDate startDate,
                                           @RequestParam LocalDate endDate){
        return productService.getStockBack(startDate,endDate);
    }



    @PostMapping("/batch/status")
    public JsonResult<String> batchUpdateStatus(@RequestBody BatchStatusRequest request) {
        return productService.batchUpdateStatus(request.getProductIds(),request.getStatus());
    }


    @PostMapping("/batch/hot")
    public JsonResult<String> batchUpdateHot(@RequestBody BatchHotRequest request) {
        return productService.batchUpdateHot(request.getProductIds(),request.getIsHot());
    }

    @PostMapping("/batch/delete")
    public JsonResult<String> batchDelete(@RequestBody List<Long> productIds) {
        return productService.batchDelete(productIds);
    }


    @PostMapping("/batch/stock")
    public JsonResult<String> batchStock(@RequestBody BatchStockRequest request) {
        return productService.batchUpdateStock(request.getProductIds(),request.getOperationType(),request.getAmount());
    }


    //导入导出相关接口
    @GetMapping("/export")
    public void exportProducts(HttpServletResponse response,
                               @RequestParam(required = false) String keyword,
                               @RequestParam(required = false) Long brandId,
                               @RequestParam(required = false) Long categoryId,
                               @RequestParam(required = false) Integer status,
                               @RequestParam(required = false) Integer isHot
                               ) {
       productService.exportProducts(response,keyword,brandId,categoryId,status,isHot);
    }

    @PostMapping("/import")
    public JsonResult<String> importProducts(@RequestParam("file") MultipartFile file) {
        return productService.importProducts(file);
    }

    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        productService.downloadTemplate(response);
    }

    //商品克隆相关接口
    @PostMapping("/{id}/clone")
    public JsonResult<String> cloneProduct(@PathVariable Long id,@RequestBody CloneRequest request) {
        System.out.println("商品克隆请求，原商品ID: {}, 克隆数量: {}, 命名规则: {}"+
                id + request.getCount() +  request.getNamingRule());
        return productService.cloneProduct(id, request);

    }

    //=========================商品组合相关接口=================================
    /*
    * 创建商品组合*/
    @PostMapping("/bundle")
    public JsonResult<String> createBundle(@RequestBody ProductBundleRequest request) {
        System.out.println("创建商品组合请求，组合名称: {}, 商品数量: {}, 组合价格: {}" +
                request.getName() + request.getSelectedProducts().size() +request.getPrice());
        return  productService.createBundle(request);
    }

    /*
    * 获取组合分页列表*/
/*    @GetMapping("/bundles")
    public JsonResult<Map<String,Object>> getBundleList(@RequestParam(value = "keyword",required = false) String keyword,
                                                        @RequestParam(value = "status",required = false ) String status,
                                                        @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                        @RequestParam(value = "size", defaultValue = "10") Integer size) {
        return productService.getBundleList(keyword,status,page,size);
    }*/
/*

    */
/*获得商品组合详情*//*

    @GetMapping("/bundle/{id}")
    public JsonResult<ProductBundle> getBundleById(@PathVariable(value = "id" ) Long id) {
        return productService.getBundleById(id);
    }


    */
/*获取商品组合包含的商品列表*//*

    public
*/










}
